package com.yhn.init.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhn.init.common.DeleteRequest;
import com.yhn.init.common.ErrorCode;
import com.yhn.init.exception.BusinessException;
import com.yhn.init.exception.ThrowUtils;
import com.yhn.init.mapper.OrdersMapper;
import com.yhn.init.model.dto.orders.OrdersAddRequest;
import com.yhn.init.model.dto.orders.OrdersConfirmedRequest;
import com.yhn.init.model.dto.orders.OrdersQueryRequest;
import com.yhn.init.model.dto.orders.OrdersUpdateRequest;
import com.yhn.init.model.entity.Orders;
import com.yhn.init.model.enums.OrderStatusEnum;
import com.yhn.init.model.vo.LoginUserVO;
import com.yhn.init.model.vo.OrdersVO;
import com.yhn.init.service.OrdersService;
import com.yhn.init.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单业务类
 *
 * @author yhnyhn123
 */
@Slf4j
@Service("ordersService")
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Resource
    private UserService userService;


    @Override
    public Page<OrdersVO> queryPage(OrdersQueryRequest ordersQueryRequest) {
        if (ordersQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = ordersQueryRequest.getCurrent();
        long size = ordersQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Orders> ordersPage = this.page(new Page<>(current, size),
                this.getQueryWrapper(ordersQueryRequest));
        Page<OrdersVO> ordersVOPage = new Page<>(current, size, ordersPage.getTotal());
        List<OrdersVO> ordersVO = this.getOrdersVO(ordersPage.getRecords());
        ordersVOPage.setRecords(ordersVO);
        return ordersVOPage;
    }


    @Override
    public QueryWrapper<Orders> getQueryWrapper(OrdersQueryRequest ordersQueryRequest) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        // 如果请求对象为空，直接返回一个空的查询包装器
        if (ordersQueryRequest == null) {
            return queryWrapper;
        }
        // 从请求对象中获取各项查询条件
        Long id = ordersQueryRequest.getId();
        queryWrapper.eq(id != null && id > 0, "id", id);
        return queryWrapper;
    }

    /**
     * 获取脱敏对象集合
     *
     * @param ordersList 查询请求
     * @return 脱敏对象集合
     */
    @Override
    public List<OrdersVO> getOrdersVO(List<Orders> ordersList) {
        if (CollUtil.isEmpty(ordersList)) {
            return new ArrayList<>();
        }
        return ordersList.stream().map(this::getOrdersVO).collect(Collectors.toList());
    }


    /**
     * 将对象转化为脱敏对象
     *
     * @param orders 原对象
     * @return 脱敏对象
     */
    @Override
    public OrdersVO getOrdersVO(Orders orders) {
        if (orders == null) {
            return null;
        }
        OrdersVO ordersVO = new OrdersVO();
        BeanUtils.copyProperties(orders, ordersVO);
        return ordersVO;
    }

    /**
     * 根据ID获取信息
     *
     * @param id id
     * @return 实体信息
     */
    @Override
    public OrdersVO getInfoById(Long id) {
        Orders orders = this.getById(id);
        if (orders == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "没有对应的信息");
        }
        return getOrdersVO(orders);
    }

    /**
     * 保存信息
     *
     * @param ordersAddRequest 添加请求
     * @return 新生成的ID
     */
    @Override
    @Transactional
    public Long saveOrders(OrdersAddRequest ordersAddRequest) {
        if (ordersAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersAddRequest, orders);
        LoginUserVO loginUser = userService.getLoginUser();
        orders.setContractId(this.generateOrderNo());
        orders.setUserId(loginUser.getId());
        orders.setOrderStatus(OrderStatusEnum.CREATED.getValue());
        boolean result = this.save(orders);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return orders.getId();
    }


    /**
     * 修改信息
     *
     * @param ordersUpdateRequest 修改请求
     * @return 是否修改成功
     */
    @Override
    @Transactional
    public Boolean updateOrders(OrdersUpdateRequest ordersUpdateRequest) {
        if (ordersUpdateRequest == null || ordersUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersUpdateRequest, orders);
        long id = ordersUpdateRequest.getId();
        // 判断是否存在
        Orders oldOrders = this.getById(id);
        ThrowUtils.throwIf(oldOrders == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = this.updateById(orders);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return result;
    }

    /**
     * 删除信息
     *
     * @param deleteRequest 删除请求
     * @return 是否修改成功
     */
    @Override
    public Boolean deleteById(DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        boolean b = this.removeById(id);
        ThrowUtils.throwIf(!b, ErrorCode.NOT_FOUND_ERROR);
        return b;

    }


    /**
     * 批量删除
     *
     * @param ids 批量删除的IDS
     * @return 是否删除成功
     */
    @Override
    @Transactional
    public Boolean deleteBatchByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = this.removeByIds(Arrays.asList(ids));
        ThrowUtils.throwIf(!b, ErrorCode.NOT_FOUND_ERROR);
        return b;
    }

    @Override
    public Boolean confirmOrders(OrdersConfirmedRequest ordersConfirmedRequest) {
        if (ordersConfirmedRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Orders orders = this.getById(ordersConfirmedRequest.getOrderId());
        // 设置订单状态
        orders.setOrderStatus(ordersConfirmedRequest.getIsConfirmed() ?
                OrderStatusEnum.FINISHED.getValue() : OrderStatusEnum.EXCEPTION.getValue());
        // 更新订单状态
        return updateOrderStatus(orders) == 1;
    }

    /**
     * 更新订单状态
     *
     * @param orders 订单对象
     */
    private Integer updateOrderStatus(Orders orders) {
        return baseMapper.updateById(orders);
    }

    /**
     * 根据时间戳自动生成单号
     *
     * @return 生成的订单号
     */
    private String generateOrderNo() {
        // 获取当前时间戳
        LocalDateTime now = LocalDateTime.now();

        // 将时间戳转换为字符串形式（例如：年月日小时分钟秒）
        String timestampStr = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

        // 生成一个随机的UUID，取其无横线版本作为订单唯一标识符
        String uniqueId = UUID.randomUUID().toString().replace("-", "");

        // 拼接订单号，如"20230101080000-ABCD1234"
        return timestampStr + "-" + uniqueId.substring(0, 8);
    }
}
